/**
 * 用户数据同步API
 * 用于处理用户收藏、历史记录等个人数据的同步
 */

import request from './request'

/**
 * 用户数据同步API
 */
export const userDataSyncApi = {
  /**
   * 上传用户数据到服务器
   * @param {Object} syncData - 同步数据
   * @param {string} syncData.syncType - 同步类型：upload/download/merge
   * @param {Array} syncData.dataTypes - 数据类型数组：['favorite', 'history', 'like']
   * @param {Array} syncData.dataItems - 数据项数组
   * @param {Object} syncData.syncConfig - 同步配置
   * @param {string} syncData.clientVersion - 客户端版本
   * @returns {Promise} - 返回同步结果
   */
  syncUserData: (syncData) => {
    return request.post('/api/user/sync', syncData)
  },

  /**
   * 上传收藏数据
   * @param {Array} favorites - 收藏数据数组
   * @param {Object} config - 同步配置
   * @returns {Promise} - 返回同步结果
   */
  uploadFavorites: (favorites, config = {}) => {
    const syncData = {
      syncType: 'upload',
      dataTypes: ['favorite'],
      dataItems: favorites.map(fav => ({
        dataType: 'favorite',
        newsId: parseInt(fav.newsId || fav.id),
        newsTitle: fav.title,
        newsUrl: fav.url,
        newsCategory: fav.category,
        newsSection: fav.section,
        extraData: {
          tags: fav.tags || [],
          note: fav.note || '',
          favoriteTime: fav.favoriteTime || new Date().toISOString()
        },
        createTime: fav.createTime || new Date().toISOString()
      })),
      syncConfig: {
        overwriteConflicts: config.overwriteConflicts || false,
        maxSyncCount: config.maxSyncCount || 1000,
        conflictResolution: config.conflictResolution || 'keep_latest'
      },
      clientVersion: '1.0.0'
    }
    return request.post('/api/user/sync', syncData)
  },

  /**
   * 上传浏览历史
   * @param {Array} history - 历史数据数组
   * @param {Object} config - 同步配置
   * @returns {Promise} - 返回同步结果
   */
  uploadHistory: (history, config = {}) => {
    const syncData = {
      syncType: 'upload',
      dataTypes: ['history'],
      dataItems: history.map(item => ({
        dataType: 'history',
        newsId: parseInt(item.newsId || item.id),
        newsTitle: item.title,
        newsUrl: item.url,
        newsCategory: item.category,
        newsSection: item.section,
        extraData: {
          readDuration: item.readDuration || 0,
          scrollPercentage: item.scrollPercentage || 0,
          visitCount: item.visitCount || 1,
          lastVisitTime: item.lastVisitTime || new Date().toISOString()
        },
        createTime: item.createTime || new Date().toISOString()
      })),
      syncConfig: {
        overwriteConflicts: config.overwriteConflicts || true, // 历史记录通常覆盖
        maxSyncCount: config.maxSyncCount || 500,
        conflictResolution: config.conflictResolution || 'keep_latest'
      },
      clientVersion: '1.0.0'
    }
    return request.post('/api/user/sync', syncData)
  },

  /**
   * 下载用户数据
   * @param {Array} dataTypes - 要下载的数据类型
   * @returns {Promise} - 返回下载的数据
   */
  downloadUserData: (dataTypes = ['favorite', 'history']) => {
    const syncData = {
      syncType: 'download',
      dataTypes: dataTypes,
      clientVersion: '1.0.0'
    }
    return request.post('/api/user/sync', syncData)
  },

  /**
   * 直接删除单个收藏
   * @param {number} newsId - 文章ID
   * @returns {Promise} - 返回删除结果
   */
  deleteFavorite: (newsId) => {
    const syncData = {
      syncType: 'delete',
      dataTypes: ['favorite'],
      dataItems: [{
        dataType: 'favorite',
        newsId: parseInt(newsId),
        action: 'delete'
      }],
      clientVersion: '1.0.0'
    }

    return request.post('/api/user/sync', syncData)
  },

  /**
   * 合并同步用户数据
   * @param {Object} localData - 本地数据
   * @param {Array} dataTypes - 数据类型
   * @param {Object} config - 同步配置
   * @returns {Promise} - 返回合并结果
   */
  mergeUserData: (localData, dataTypes = ['favorite', 'history'], config = {}) => {
    const dataItems = []
    
    // 处理收藏数据
    if (dataTypes.includes('favorite') && localData.favorites) {
      dataItems.push(...localData.favorites.map(fav => ({
        dataType: 'favorite',
        newsId: parseInt(fav.newsId || fav.id),
        newsTitle: fav.title,
        newsUrl: fav.url,
        newsCategory: fav.category,
        newsSection: fav.section,
        extraData: fav.extraData || {},
        createTime: fav.createTime || new Date().toISOString()
      })))
    }

    // 处理历史数据
    if (dataTypes.includes('history') && localData.history) {
      dataItems.push(...localData.history.map(item => ({
        dataType: 'history',
        newsId: parseInt(item.newsId || item.id),
        newsTitle: item.title,
        newsUrl: item.url,
        newsCategory: item.category,
        newsSection: item.section,
        extraData: item.extraData || {},
        createTime: item.createTime || new Date().toISOString()
      })))
    }

    const syncData = {
      syncType: 'merge',
      dataTypes: dataTypes,
      dataItems: dataItems,
      syncConfig: {
        overwriteConflicts: config.overwriteConflicts || false,
        maxSyncCount: config.maxSyncCount || 1000,
        deleteLocalMissing: config.deleteLocalMissing || false,
        conflictResolution: config.conflictResolution || 'keep_latest'
      },
      clientVersion: '1.0.0'
    }
    return request.post('/api/user/sync', syncData)
  },

  /**
   * 获取用户数据统计
   * @returns {Promise} - 返回统计信息
   */
  getUserDataStats: () => {
    return request.get('/api/user/data/stats')
  },

  /**
   * 清理过期历史记录
   * @param {number} keepDays - 保留天数，默认30天
   * @returns {Promise} - 返回清理结果
   */
  cleanExpiredHistory: (keepDays = 30) => {
    return request.delete(`/api/user/data/history/cleanup?keepDays=${keepDays}`)
  }
}

/**
 * 数据同步工具类
 */
export class UserDataSyncManager {
  constructor() {
    this.isOnline = navigator.onLine
    this.syncQueue = []
    this.lastSyncTime = localStorage.getItem('lastSyncTime')
    
    // 监听网络状态
    window.addEventListener('online', () => {
      this.isOnline = true
      this.processSyncQueue()
    })
    
    window.addEventListener('offline', () => {
      this.isOnline = false
    })
  }

  /**
   * 添加到同步队列
   */
  addToSyncQueue(syncData) {
    this.syncQueue.push({
      ...syncData,
      timestamp: Date.now()
    })
    
    if (this.isOnline) {
      this.processSyncQueue()
    }
  }

  /**
   * 处理同步队列
   */
  async processSyncQueue() {
    if (!this.isOnline || this.syncQueue.length === 0) {
      return
    }

    const syncItem = this.syncQueue.shift()
    try {
      await userDataSyncApi.syncUserData(syncItem)
      console.log('数据同步成功:', syncItem)
      
      // 更新最后同步时间
      this.lastSyncTime = new Date().toISOString()
      localStorage.setItem('lastSyncTime', this.lastSyncTime)
      
      // 继续处理队列
      if (this.syncQueue.length > 0) {
        setTimeout(() => this.processSyncQueue(), 1000) // 延迟1秒避免频繁请求
      }
    } catch (error) {
      console.error('数据同步失败:', error)
      // 重新加入队列，但限制重试次数
      if (!syncItem.retryCount) {
        syncItem.retryCount = 0
      }
      if (syncItem.retryCount < 3) {
        syncItem.retryCount++
        this.syncQueue.unshift(syncItem) // 重新加入队列头部
      }
    }
  }

  /**
   * 立即同步
   */
  async syncNow(syncData) {
    if (!this.isOnline) {
      this.addToSyncQueue(syncData)
      return { success: false, message: '网络不可用，已加入同步队列' }
    }

    try {
      const result = await userDataSyncApi.syncUserData(syncData)
      this.lastSyncTime = new Date().toISOString()
      localStorage.setItem('lastSyncTime', this.lastSyncTime)
      return result
    } catch (error) {
      console.error('立即同步失败:', error)
      this.addToSyncQueue(syncData)
      throw error
    }
  }

  /**
   * 获取同步状态
   */
  getSyncStatus() {
    return {
      isOnline: this.isOnline,
      queueLength: this.syncQueue.length,
      lastSyncTime: this.lastSyncTime
    }
  }
}

// 创建全局同步管理器实例
export const syncManager = new UserDataSyncManager()

export default userDataSyncApi
